module.exports = app => {
  const express = require('express')
  app.use(express.json()) // post解析json
  const ws = require('nodejs-websocket')
  let number = 0
  
  const serve = ws.createServer(socket => {
    const data = {
      code: 0,
      msg: '连接成功',
      number
    }
    serve.connections.forEach((item, index) => { // 连接成功一个将掉线的清除
      console.log(item.path) // 链接地址
      data.url = '/node/socket/用户：' + item.path.split('socket/')[1]
      if (!item.readyState) item.close()
      if (index === 0) return
      if (serve.connections[index - 1].path === serve.connections[index].path) serve.connections[index - 1].close()
    })
    console.log('连接成功，当前人数' + serve.connections.length)
    number = serve.connections.length
    data.number = serve.connections.length
    sendMessage(JSON.stringify(data))

    socket.on('text', data => {
      let msg = null
      try {
        msg = JSON.parse(data)
      } catch (e) {
        msg = data
      }
      if (msg.message !== 'header' && typeof msg === 'object') {
        msg.code = 200
        msg.number = number
      }
      console.log(msg)
      if (msg.privateHair) sendMessage(JSON.stringify(msg), true)
      else sendMessage(JSON.stringify(msg))
    })

    socket.on('close', () => {
      number--
      const data = {
        code: 0,
        msg: '用户退出',
        number
      }
      sendMessage(JSON.stringify(data))
    })
    
    socket.on('error', err => {
      console.log(err ? '用户退出。当前人数' + serve.connections.length : err)
    })
    
  }).listen(10010)

  function sendMessage (val, bolean = false) {
    if (bolean) {
      const index = JSON.parse(val).privateHair
      serve.connections.forEach(item => {
        console.log(index, item.path.split('socket/')[1])
        if (index === item.path.split('socket/')[1]) {
          item.send(val)
        }
      })
      return
    }
    serve.connections.forEach(item => {
      item.send(val)
    })
  }
}
